import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;

public class Solution {
    public int totalFruit(int[] fruits) {
        int n = fruits.length;
        int ret = 0;//记录可以收集的水果的最大数目
        int left = 0, right = 0;
        HashMap<Integer, Integer> hm = new HashMap<>();//k为水果类型，v为类型个数
        while(right < n){
            //入窗口
            int fruit = fruits[right];
            if(hm.containsKey(fruit)){
                //水果类型存在，更新value
                Integer num = hm.get(fruit);
                hm.put(fruit, num);
            }else{
                hm.put(fruit, 1);
            }

            while(hm.size() > 2){
                //出窗口
                hm.put(fruits[left], hm.get(fruits[left]) - 1);
                if(hm.get(fruits[left]) == 0){
                    hm.remove(fruits[left]);
                }
                left++;
            }
            ret = Math.max(ret, right - left + 1);
            right++;
        }
        return ret;
    }
}